"use strict";
$(function () {
    yams.menu.select('checkmeter');

    yams.page = {
        /**
         * 初始化页面
         */
        init: function () {
            Dolphin.form.parse();
            this.initDataList();
            this.initEvent();
            this.selectMonth = null;
        },

        initEvent: function () {
            let me = this;
            $(".js-example-basic-single").select2();

            //查询
            $(".btn-query").click(function () {
                let condition = Dolphin.form.getValue('.query-form');
                let meterDate = $("#meterDate").val();
                if (meterDate) {
                    condition.meterYear = meterDate.split("-")[0];
                    condition.meterMonth = parseInt(meterDate.split("-")[1]) + '';
                    $("#meterYear").val(condition.meterYear);
                    $("#meterMonth").val(condition.meterMonth);
                }
                condition.filterFlag = 0;
                me._dataList.load('/api/ae5b4154f12b4ad5a074eaefec306131', condition);
            });

            //过滤出未抄表记录
            $(".btn-filter").click(function () {
                let condition = Dolphin.form.getValue('.query-form');
                let meterDate = $("#meterDate").val();
                if (meterDate) {
                    condition.meterYear = meterDate.split("-")[0];
                    condition.meterMonth = parseInt(meterDate.split("-")[1]) + '';
                    $("#meterYear").val(condition.meterYear);
                    $("#meterMonth").val(condition.meterMonth);
                }
                condition.filterFlag = 1;
                me._dataList.load('/api/ae5b4154f12b4ad5a074eaefec306131', condition);
            });

            //选择公寓
            $("#apartment_select").change(function () {
                let queryConditionObj = {};
                queryConditionObj.apartment_id_obj_ae = $(this).val();
                let _this = $("#house_select").empty();
                Dolphin.ajax({
                    url: '/api/9651431c68a04d54a22f1e2e7faf827b',
                    type: Dolphin.requestMethod.POST,
                    data: Dolphin.json2string({properties: queryConditionObj}),
                    onSuccess: function (reData) {
                        _this.append('<option value="">--请选择--</option>');
                        $.each(reData.rows, function (index, obj) {
                            _this.append('<option value="' + obj.id + '">' + obj.name + '</option>');
                        });
                    }
                });
            });

            //批量保存
            $("#batchSave").click(function () {
                let checkedData = me._dataList.getChecked();
                if (checkedData.length < 1) {
                    Dolphin.alert("请至少选择一条记录进行保存");
                    return;
                }
                console.log(checkedData);
                $.each(checkedData, function (i, obj) {
                    let meterDate = $("#meterDate").val();
                    if (meterDate) {
                        obj.meterDay = new Date().getDate() + '';
                    } else {
                        Dolphin.alert("没有抄表日期,无法保存");
                        return;
                    }
                    if (!obj.id) {
                        let $tr = $("#dataList").find("tr[__id__='" + obj.__id__ + "']");
                        obj.water = $tr.find("input[name='water']").val();
                        obj.gas = $tr.find("input[name='gas']").val();
                        obj.electric = $tr.find("input[name='electric']").val();
                        Dolphin.ajax({
                            url: '/api/509cb2a903d2466b9645432e02506141',
                            type: Dolphin.requestMethod.PUT,
                            data: Dolphin.json2string(obj),
                            async: false,
                            onSuccess: function (reData) {

                            }
                        });
                    }
                });
                $(".btn-query").click();
            });

            //批量生成账单
            $("#batchGenBill").click(function () {

                let checkedData = me._dataList.getChecked();
                if (checkedData.length < 1) {
                    Dolphin.alert("请至少选择一条记录进行账单的生成");
                    return;
                }
                console.log(checkedData);
                Dolphin.confirm('确认生成水电费账单吗，请谨慎操作，<strong style="color: red;">不要重复</strong>生成账单？', {
                    width:'450px',
                    callback: function (flag) {
                        if (flag) {
                            $.each(checkedData, function (i, obj) {
                                if (obj.id) {
                                    Dolphin.ajax({
                                        url: '/api/ff0163fa93fb490da256aef5b01b0844',
                                        type: Dolphin.requestMethod.PUT,
                                        data: Dolphin.json2string(obj),
                                        async: false,
                                        onSuccess: function (reData) {

                                        }
                                    });
                                }
                            });
                            $(".btn-query").click();
                        }
                    }
                })
            });

            $("#meterDateSelect").change(function () {
                this.selectMonth = $(this).val();
                let m = this.selectMonth.split("-");
                me._dataList.load('/api/ae5b4154f12b4ad5a074eaefec306131', {
                    meterYear: m[0],
                    meterMonth: Number(m[1]) + "",
                    status: 1,
                    filterFlag:0
                });
            }).change();

            $("#printBill").click(function () {
                $("#printContent").html($("#dataList").html());
                $('#printModal').modal('show');
            });

            $(".printContract").click(function (){
                $('#printContent').printThis();
            });
        },

        initDataList: function () {
            let me = this;
            me._dataList = new Dolphin.LIST({
                panel: "#dataList",
                idField: 'id',
                columns: [{
                    code: 'houseIdentites',
                    title: '房屋名称',
                    formatter: function (val) {
                        return val;
                    }
                }, {
                    code: 'lastMeterInfo',
                    title: '上次抄表数据',
                    width: '200px',
                    formatter: function (val, row) {
                        let vv = val.split(','), html = [];
                        html.push("<div>水费：");
                        html.push(vv[0]);
                        html.push("</div><div>电费：");
                        html.push(vv[1]);
                        html.push("</div><div>气费：");
                        html.push(vv[2]);
                        html.push("</div>");
                        row._water = vv[0];
                        row._electric = vv[1];
                        row._gas = vv[2];
                        return html.join("");
                    }
                }, {
                    code: 'meterMonth',
                    title: '抄表月份',
                    width: '120px',
                    formatter: function (val) {
                        return val || me.selectMonth;
                    }
                }, {
                    code: 'water',
                    title: '本月水表',
                    width: '130px',
                    formatter: function (val, row) {
                        let input = $('<input class="form-control" data-code="' + row.code + '" placeholder="" name="water" type="text">');
                        input.val(row.water);
                        input.change(function () {
                            let v = $(this).val();
                            if (!v) {
                                return;
                            }
                            if (v < row._water) {
                                $(this).val('');
                                return;
                            }
                            Dolphin.ajax({
                                url: '/api/509cb2a903d2466b9645432e02506141',
                                type: Dolphin.requestMethod.PUT,
                                data: Dolphin.json2string({
                                    code: row.code,
                                    houseId: row.houseId,
                                    meterYear: row.meterYear,
                                    meterMonth: Number(row.meterMonth),
                                    meterDay: row.meterYear + '-' + row.meterMonth + '-01',
                                    water: v
                                }),
                                onSuccess: function (reData) {
                                }
                            });
                        });
                        return input;
                    }
                }, {
                    code: 'electric',
                    title: '本月电表',
                    width: '130px',
                    formatter: function (val, row) {
                        let input = $('<input class="form-control" data-code="' + row.code + '" placeholder="" name="electric" type="text">');
                        input.val(row.electric);
                        input.change(function () {
                            let v = $(this).val();
                            if (!v) {
                                return;
                            }
                            if (v < row._electric) {
                                $(this).val('');
                                return;
                            }
                            Dolphin.ajax({
                                url: '/api/509cb2a903d2466b9645432e02506141',
                                type: Dolphin.requestMethod.PUT,
                                data: Dolphin.json2string({
                                    code: row.code,
                                    houseId: row.houseId,
                                    meterYear: row.meterYear,
                                    meterMonth: Number(row.meterMonth),
                                    meterDay: row.meterYear + '-' + row.meterMonth + '-01',
                                    electric: v
                                }),
                                onSuccess: function (reData) {
                                }
                            });
                        });
                        return input;
                    }
                }, {
                    code: 'gas',
                    title: '本月燃气',
                    width: '130px',
                    formatter: function (val, row) {
                        let input = $('<input class="form-control" data-code="' + row.code + '" placeholder="" name="gas" type="text">');
                        input.val(row.gas);
                        input.change(function () {
                            let v = $(this).val();
                            if (!v) {
                                return;
                            }
                            if (v < row._gas) {
                                $(this).val('');
                                return;
                            }
                            Dolphin.ajax({
                                url: '/api/509cb2a903d2466b9645432e02506141',
                                type: Dolphin.requestMethod.PUT,
                                data: Dolphin.json2string({
                                    code: row.code,
                                    houseId: row.houseId,
                                    meterYear: row.meterYear,
                                    meterMonth: Number(row.meterMonth),
                                    meterDay: row.meterYear + '-' + row.meterMonth + '-01',
                                    gas: v
                                }),
                                onSuccess: function (reData) {

                                }
                            });
                        });
                        return input;
                    }
                }],
                multiple: true,
                rowIndex: true,
                checkbox: true,
                ajaxType: Dolphin.requestMethod.POST,
                queryParams: {
                    pageSize: 10000,
                    pageNumber: 0,
                    _manager : yams.context.checkAdmin()
                },
                pagination: false,
                onLoadSuccess: function (data) {
                    //点击保存
                    $('.saveBtn').click(function () {
                        let obj = {};
                        let doms = $(this).closest("tr").find("input[gps]");
                        $.each(doms, function (i, n) {
                            let key = $(n).attr("name");
                            let value = $(n).val();
                            obj[key] = value;
                        });
                        let meterDate = $("#meterDate").val();
                        if (meterDate) {
                            obj.meterYear = meterDate.split("-")[0];
                            obj.meterMonth = parseInt(meterDate.split("-")[1]) + '';
                            obj.meterDay = new Date().getDate() + '';
                        } else {
                            Dolphin.alert("没有抄表日期,无法保存");
                            return;
                        }
                        Dolphin.ajax({
                            url: '/api/509cb2a903d2466b9645432e02506141',
                            type: Dolphin.requestMethod.PUT,
                            data: Dolphin.json2string(obj),
                            onSuccess: function (reData) {
                                $(".btn-query").click();
                            }
                        });
                    });

                    //生成账单
                    $('.genBillBtn').click(function () {
                        let obj = {};
                        let doms = $(this).closest("tr").find("input[gps]");
                        $.each(doms, function (i, n) {
                            let key = $(n).attr("name");
                            let value = $(n).val();
                            obj[key] = value;
                        });
                        Dolphin.confirm('确认生成水电费账单吗，请谨慎操作，不要重复生成账单？', {
                            callback: function (flag) {
                                if (flag) {
                                    Dolphin.ajax({
                                        url: '/api/ff0163fa93fb490da256aef5b01b0844',
                                        type: Dolphin.requestMethod.PUT,
                                        data: Dolphin.json2string(obj),
                                        onSuccess: function (reData) {
                                            $(".btn-query").click();
                                        }
                                    });
                                }
                            }
                        })


                    });

                    //点击编辑
                    $('.editBtn').click(function () {

                        let _water = $($(this).closest("tr").find("td[columncode='water']")[0]);
                        let _waterVal = _water.html();
                        let _electric = $($(this).closest("tr").find("td[columncode='electric']")[0]);
                        let _electricVal = _electric.html();
                        let _gas = $($(this).closest("tr").find("td[columncode='gas']")[0]);
                        let _gasVal = _gas.html();
                        _water.html('<input type="text" gps="1" name="water" value="' + _waterVal + '" />');
                        _electric.html('<input type="text"  gps="1" name="electric" value="' + _electricVal + '" />');
                        _gas.html('<input type="text" gps="1" name="gas" value="' + _gasVal + '" />');

                        $('<a class="btn btn-outline btn-circle btn-sm green saveBtn" href="javascript:;">' +
                            '<i class="fa fa-save"></i>保存</a>').click(function () {

                            let obj = {};
                            let doms = $(this).closest("tr").find("input[gps]");
                            $.each(doms, function (i, n) {
                                let key = $(n).attr("name");
                                let value = $(n).val();
                                obj[key] = value;
                            });
                            let meterDate = $("#meterDate").val();
                            if (meterDate) {
                                obj.meterYear = meterDate.split("-")[0];
                                obj.meterMonth = parseInt(meterDate.split("-")[1]) + '';
                                obj.meterDay = new Date().getDate() + '';
                            } else {
                                Dolphin.alert("没有抄表日期,无法保存");
                                return;
                            }
                            Dolphin.ajax({
                                url: '/api/509cb2a903d2466b9645432e02506141',
                                type: Dolphin.requestMethod.PUT,
                                data: Dolphin.json2string(obj),
                                onSuccess: function (reData) {
                                    $(".btn-query").click();
                                }
                            });
                        }).insertAfter($(this));
                        $(this).remove();
                    });
                }
            });
        },

        /**
         * 一些页面DOM对象和事件的销毁
         */
        destroy: function () {
        }
    }
});